
/**
 * @ProjectName: 
 * @Copyright: 2014 lisheng  All Right Reserved.
 * @address: toughheart@163.com
 * @date: 2016年2月28日 下午8:26:17
 * @Description: 本内容未经本人允许禁止使用、转发.
 */
 
package com.ls.fw.web.core.support;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;



/**
 * 
 * @author lisheng
 * @date 2016年2月28日 下午8:26:17
 * @version V1.0 
 */
public class DetaultTokenManager implements TokenManager<HttpSession>{

    /**
     * The token parameter name
     */
    static final String PARAM_NAME = "_token";
 
    /**
     * The location on the session which stores the token
     */
    public static final  String TOKEN_FOR_SESSION_ATTR_NAME = DetaultTokenManager.class
            .getName() + ".tokenval";
    
    private String name = PARAM_NAME;
    private String storgeName = TOKEN_FOR_SESSION_ATTR_NAME;
    
    
	@Override
	public String getTokenForSession(HttpSession session) {
		String token = null;
        // I cannot allow more than one token on a session - in the case of two
        // requests trying to
        // init the token concurrently
        synchronized (session) {
            token = (String) session
                    .getAttribute(getStorgeName());
            if (null == token) {
                token = UUID.randomUUID().toString();
                session.setAttribute(getStorgeName(), token);
            }
        }
        return token;
	}

	@Override
	public String getTokenFromStorage(HttpSession storage,
			HttpServletRequest request) {
		String token = null;
        token = (String) storage
                .getAttribute(getStorgeName());
        return token;
	}

	@Override
	public String getTokenFromRequest(HttpServletRequest request) {
		 String token = "";
         token = request.getHeader(this.getName());
         if(org.apache.commons.lang3.StringUtils.isBlank(token)){
         	token = request.getParameter(this.getName());
         }
         return token;
	}
	
	@Override
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String getStorgeName() {
		return storgeName;
	}

	public void setStorgeName(String storgeName) {
		this.storgeName = storgeName;
	}
}
